package com.itheima.test5;

import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author:gy
 * @Date: 2025/09/03 14:52
 * @Description:
 */
public class MyThread extends Thread {
    //在外面定义一个集合
    private static ArrayList<String> list = new ArrayList();
    //个人存放礼物的集合
    private ArrayList<String> al = new ArrayList();

    public ArrayList<String> getAl() {
        return al;
    }

    public void setAl(ArrayList<String> al) {
        this.al = al;
    }

    static{
        list.add("电视机");
        list.add("电冰箱");
        list.add("电脑");
        list.add("游戏机");
        list.add("空调");
        list.add("手机");
        list.add("洗衣机");
        list.add("平板电脑");
        list.add("电动车");
        list.add("电饭煲");
    }
    //抽奖人的姓名
    private String name;

    public MyThread(String name) {
        this.name = name;
    }

    //锁
    private static Lock lock = new ReentrantLock();
    @Override
    public void run() {
        //随机索引  就是随机奖品
        Random random = new Random();
        while (!list.isEmpty()) {
            lock.lock();
            try {
                if(list.isEmpty()){
                    break;
                }
                //随机一个奖品 其实就是随机索引
                int index = random.nextInt(list.size());
                //直接将奖品删除 返回值就是这个奖品本身
                String remove = list.remove(index);
                System.out.println("恭喜" + name + "抽到了" + remove);
                al.add(remove);

            } catch (RuntimeException e) {
                throw new RuntimeException(e);
            }  finally {
                lock.unlock();
            }
            try {
                Thread.sleep(random.nextInt(100));
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
